var User_Form = function () {
    var handleValidation_Profile = function() {

        var form_profile = $('#form-profile');
        var error_profile = $('.alert-error');

        form_profile.validate({
            errorElement: 'span', //default input error message container
            errorClass: 'help-inline', // default input error message class
            focusInvalid: false, // do not focus the last invalid input
            ignore: "",
            rules: {
                username: {
                    minlength: 10,
                    required: true
                },
                birthday: {
                    regex: /(\d{2})-(\d{2})-(\d{4})/
                },
                baptism_date: {
                    regex: /[0-9][0-9]-[0-1][0-9]-[1-2][0-9][0-9][0-9]/
                },
                eucharist_date: {
                    regex: /[0-9][0-9]-[0-1][0-9]-[1-2][0-9][0-9][0-9]/
                },
                confirmation_date: {
                    regex: /[0-9][0-9]-[0-1][0-9]-[1-2][0-9][0-9][0-9]/
                },
                email: {
                    email: true
                },
                passwd: {
                    minlength: 6,
                    regex: /(?=.*\d)(?=.*[a-zA-Z]).{6,}/,
                    required: true
                },
                retypepasswd: {
                    minlength: 6,
                    required: true,
                    equalTo : "#passwd"
                }
            },
            messages: {
                username: {
                    minlength: 'Tối thiểu 10 ký tự',
                    required: 'Bắt buộc nhập'
                },
                email: {
                    email: 'Email không hợp lệ'
                },
                passwd: {
                    minlength: 'Tối thiểu 6 ký tự',
                    required: 'Bắt buộc nhập',
                    regex: "Mật Khẩu phải chứa ký tự số <strong>0-9</strong> và chữ cái <strong>a-Z</strong>"
                },
                retypepasswd: {
                    minlength: 'Tối thiểu 6 ký tự',
                    required: 'Bắt buộc nhập',
                    equalTo : "Chưa khớp với Mât Khẩu Mới"
                }
            },
            invalidHandler: function (event, validator) { //display error alert on form submit              
                error_profile.show();
                App.scrollTo(error_profile, -200);
            },
            highlight: function (element) { // hightlight error inputs
                $(element)
                .closest('.help-inline').removeClass('ok'); // display OK icon
                $(element)
                .closest('.control-group').removeClass('success').addClass('error'); // set error class to the control group
            },
            unhighlight: function (element) { // revert the change done by hightlight
                $(element)
                .closest('.control-group').removeClass('error'); // set error class to the control group
            },
            success: function (label) {
                label
                .closest('.control-group').removeClass('error').addClass('success').end()
                .remove(); // set success class to the control group
            },
            submitHandler: function (form) {
                error_profile.hide();
                
                var tmp_string = $('#birthday', form_profile).val();
                if (tmp_string != '') {
                    tmp_string = new Date(tmp_string.replace(/(\d+)-(\d+)-(\d+)/, '$3-$2-$1'));
                    $('#birthday', form_profile).val($.datepicker.formatDate('yy-mm-dd', tmp_string));
                }
                
                var tmp_string = $('#baptism_date', form_profile).val();
                if (tmp_string != '') {
                    tmp_string = new Date(tmp_string.replace(/(\d+)-(\d+)-(\d+)/, '$3-$2-$1'));
                    $('#baptism_date', form_profile).val($.datepicker.formatDate('yy-mm-dd', tmp_string));
                }
                
                var tmp_string = $('#eucharist_date', form_profile).val();
                if (tmp_string != '') {
                    tmp_string = new Date(tmp_string.replace(/(\d+)-(\d+)-(\d+)/, '$3-$2-$1'));
                    $('#eucharist_date', form_profile).val($.datepicker.formatDate('yy-mm-dd', tmp_string));
                }
                
                var tmp_string = $('#confirmation_date', form_profile).val();
                if (tmp_string != '') {
                    tmp_string = new Date(tmp_string.replace(/(\d+)-(\d+)-(\d+)/, '$3-$2-$1'));
                    $('#confirmation_date', form_profile).val($.datepicker.formatDate('yy-mm-dd', tmp_string));
                }

                form.submit();
            }
        });
    }
    
    var FormWinzard = function() {
        var form_file = $('#form-file');
        var error = $('.alert-error-file');
        var success = $('.alert-success-file');
        
        $(':file').fileupload({
            dataType: 'json',
            beforeSend: function (e, data) {
                
                form_wizard.find('.upload-bar').css({
                    width: '0%'
                }).parent().show();
                
                $('.btn-file').hide();
            },
            done: function (e, response) {
                
                if (response.result.code == 200) {
                    form_wizard.find('.upload-bar').css({
                        width: '100%'
                    });
                
                    form_wizard.find('.button-next').trigger('click');
                
                    $('.course', '#form-info').val( response.result.data.course);
                    $('.usertype', '#form-info').val( response.result.data.usertype);
                    $('#body-tmp').html( tmpl('user-tmpl', response.result.data.users) );
                }
            },
            fail: function (e, response) {
                form_wizard.find('.upload-bar').css({
                    width: '0%'
                }).parent().hide();
                
                $('.btn-file').show();
                
                alert('Kiểm tra lại File!');
            },
            progressall: function (e, response) {
                var progress = parseInt(response.loaded / response.total * 100, 10);
                form_wizard.find('.upload-bar').css({
                    width: progress + '%'
                });
            }
        });
        
        // default form wizard
        var form_wizard = $('#form_wizard');
        
        form_wizard.bootstrapWizard({
            'nextSelector': '.button-next',
            'previousSelector': '.button-previous',
            onTabClick: function (tab, navigation, index) {
                //                alert('Bạn chưa thực hiện được Bước này.');
                return false;
            },
            onNext: function (tab, navigation, index) {
                success.hide();
                error.hide();
                
                if (index == 2 && $('.flag-submitted', '#form-info').val() == 'false' ) {
                    
                    $.ajax({
                        url: $('#form-info').attr('action'),
                        type: $('#form-info').attr('method'),
                        data: $('#form-info').serialize(),
                        dataType: 'json'
                    }) .done(function(response) {
                        $('.flag-submitted', '#form-info').val('true');
                        
                        $('#body-complete-tmp').html( tmpl('user-complete-tmpl', response.data.users) );
                        
                        form_wizard.find('.button-next').trigger('click');
                    })
                    .fail(function() {
                        alert( "Lỗi" );
                        form_wizard.find('.button-previous, .button-next').show();
                        $('.flag-submitted', '#form-info').show();
                    });
                    
                    form_wizard.find('.button-previous, .button-next').hide();
                    $('.flag-submitted', '#form-info').hide();
                    
                    return false;
                }    
                
                var total = navigation.find('li').length;
                var current = index + 1;
                                    
                jQuery('li', form_wizard).removeClass("done");
                
                var li_list = navigation.find('li');
                for (var i = 0; i < index; i++) {
                    jQuery(li_list[i]).addClass("done");
                }

                if (current == 1) {
                    form_wizard.find('.button-previous').hide();
                } else {
                    form_wizard.find('.button-previous').show();
                }

                if (current >= total) {
                    form_wizard.find('.button-next').hide();
                    form_wizard.find('.button-submit').show();
                } else {
                    form_wizard.find('.button-next').show();
                    form_wizard.find('.button-submit').hide();
                }
                App.scrollTo($('.breadcrumb'));
            },
            onPrevious: function (tab, navigation, index) {
                success.hide();
                error.hide();

                var total = navigation.find('li').length;
                var current = index + 1;
                
                jQuery('li', form_wizard).removeClass("done");
                
                var li_list = navigation.find('li');
                for (var i = 0; i < index; i++) {
                    jQuery(li_list[i]).addClass("done");
                }

                if (current == 1) {
                    form_wizard.find('.button-previous').hide();
                } else {
                    form_wizard.find('.button-previous').show();
                }

                if (current >= total) {
                    form_wizard.find('.button-next').hide();
                    form_wizard.find('.button-submit').show();
                } else {
                    form_wizard.find('.button-next').show();
                    form_wizard.find('.button-submit').hide();
                }

                App.scrollTo($('.breadcrumb'));
            },
            onTabShow: function (tab, navigation, index) {
                var total = navigation.find('li').length;
                var current = index + 1;
                var $percent = (current / total) * 100;
                form_wizard.find('.process-bar').css({
                    width: $percent + '%'
                });
            }
        });

        form_wizard.find('.button-previous, .button-next').hide();

        $('#form_wizard .button-submit').click(function () {
            document.location.reload(true);
        }).hide();
    }

    return {
        init: function () {
            
            $.datepicker.regional['vn'] = {
                monthNamesShort: ['Tháng 1','Tháng 2','Tháng 3','Tháng 4','Tháng 5','Tháng 6','Tháng 7','Tháng 8','Tháng 9','Tháng 10','Tháng 11','Tháng 12'],
                dayNamesMin: ['Hai','Ba','Tư','Năm','Sáu','Bảy','CN'],
                dateFormat : 'dd-mm-yy',
                changeMonth: true,
                changeYear: true
            };
        
            $.datepicker.setDefaults($.datepicker.regional['vn']);
            $(".datepicker").datepicker();
            
            jQuery.validator.addMethod("regex", function (value, element, regexp) {
                var re = new RegExp(regexp);
                return this.optional(element) || re.test(value);
            },
            "Giá trị không hợp lệ"
            );
            
            handleValidation_Profile();
            FormWinzard();
            
            $('tr.user-infos').live('click', function () {
                var inputs = $("input, select", $(this));
                var obj = {};
                
                obj['tmp_userid'] = $(this).attr('userid');
                
                $.map(inputs, function(n, i) {
                    
                    obj[$(n).attr('tmp-name')] = $(n).val();
                });
                
                $('.modal-body', '#responsive').html(tmpl('user-info-tmpl', obj));
                
                $('#responsive').modal()
                .find('.btn-save').click(function () {
                    
                    var tmp_inputs = $("input, select", $('#responsive'));
                    var obj = {}, tmp_obj = {}, tmp_obj_abc = {};
                    
                    $.map(tmp_inputs, function(n, i) {
                    
                        obj[$(n).attr('name')] = $(n).val();
                    });

                    tmp_obj[obj.tmp_userid] = obj;
                    $('tr.user-infos[userid="' + obj.tmp_userid + '"]').replaceWith(tmpl('user-tmpl', tmp_obj));
                    $('.close','#responsive').click();
                });
            });
        }
    };
}();